import 'package:flutter/material.dart';
import 'package:flutter_changdian_football/api/req/ali/req_ali.dart';
import 'package:flutter_changdian_football/api/req/user/req_user.dart';
import 'package:flutter_changdian_football/pages/mine/my_purse/my_purse_controller.dart';
import 'package:flutter_changdian_football/utils/custom_constant.dart';
import 'package:flutter_changdian_football/widget/dialog/operational_results_dialog.dart';
import 'package:flutter_changdian_football/widget/toast/custom_toast.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:tobias/tobias.dart' as tobias;

class WithdrawController extends GetxController {

  WithdrawController({
    this.clubId
  });

  final String? clubId;

  @override
  void onInit() {
    super.onInit();

    getUserZfbInfo();
  }

  /// 支付宝账号
  String? alipayAccount;

  /// 获取用户绑定的支付宝信息
  getUserZfbInfo() async {
    try {
      var resp = await ReqUser.getUserZfbInfo();

      if (resp.data['code'] == '200') {
        alipayAccount = resp.data['data']['zfbNickName'];
        update();
      } else {
        CustomToast.showTextToast(resp.data['msg']);
      }
    } catch (e) {
      CustomToast.showTextToast('系统繁忙，请稍后再试！');
    } finally {
      EasyLoading.dismiss();
    }
  }

  /// 获取支付配置
  getPayProperties() async {
    if (alipayAccount != null) {
      return ;
    }
    bool result = await tobias.isAliPayInstalled();
    if (!result) {
      CustomToast.showTextToast('暂未安装支付宝');
      return ;
    }
    try {
      EasyLoading.show();
      var resp = await ReqAli.getPayProperties();

      if (resp.data['code'] == '200') {
        bindAliPayAccount(resp.data['data']['authParameters']);
      } else {
        CustomToast.showTextToast(resp.data['msg']);
      }
    } catch (e) {
      CustomToast.showTextToast('系统繁忙，请稍后再试！');
    } finally {
      EasyLoading.dismiss();
    }
  }

  /// 绑定支付宝
  bindAliPayAccount(authStr) {
    tobias.aliPayAuth(authStr).then((Map value) {
      if (int.parse(value["resultStatus"]) == 9000) {
        String result = value["result"];
        List list = result.split("&");
        list.forEach((element) {
          if (element.startsWith("auth_code=")) {
            final authCode = element.split("=")[1];
            zfbAuthorization(authCode);
          }
        });
      }
    });
  }

  /// 支付宝授权获取用户支付宝信息
  zfbAuthorization(authCode) async {
    try {
      EasyLoading.show();
      var resp = await ReqAli.zfbAuthorization(authCode: authCode);

      if (resp.data['code'] == '200') {
        alipayAccount = resp.data['data']['zfbNickName'];
        update();
      } else {
        CustomToast.showTextToast(resp.data['msg']);
      }
    } catch (e) {
      CustomToast.showTextToast('系统繁忙，请稍后再试！');
    } finally {
      EasyLoading.dismiss();
    }
  }


  TextEditingController balanceController = TextEditingController();

  /// 全部提现
  changeAllWithDraw(p) {
    balanceController.text = p;
    update();
  }

  TextEditingController reasonController = TextEditingController();

  
  String? reason;

  /// 立即提现
  zfbWithdraw({
    required String type
  }) async {
    if (balanceController.text.trim().isEmpty) {
      CustomToast.showTextToast('请输入提现金额');
      return;
    }
    if (double.parse(balanceController.text) < 1) {
      CustomToast.showTextToast('最低提现金额必须大于等于1元');
      return;
    }
    if (alipayAccount == null) {
      CustomToast.showTextToast('请先绑定支付宝');
      return;
    }

    if (clubId != null) {
      if ( reasonController.text.trim() == '') {
        CustomToast.showTextToast('请输入提现备注');
        return;
      }
    }


    // Map<String, dynamic> param = {
    //   "clubId": widget.clubId,
    //   "reason": reason,
    // };

    try {
      EasyLoading.show();
      var resp = await ReqAli.zfbWithdraw(
        withdrawAmount: balanceController.text, 
        withdrawType: type == CustomConstant.withdraw_normal ? 'PERSONAL' : 'CLUB',
        clubId: clubId,
        reason: reasonController.text
      );

      if (resp.data['code'] == '200') {
        OperationalResultsDialog.show(
          Get.context!,
          text: '提现成功',
          icon: 'assets/images/img_tc_cg.png',
          confirmTap: () {
            Get.back();
            MyPurseController.to.getUserAccountBalance();
          }
        );
      } else {
        OperationalResultsDialog.show(
          Get.context!,
          text: resp.data['msg'],
          icon: 'assets/images/img_tc_sb.png',
          confirmTap: () {
            Get.back();
          }
        );
      }
    } catch (e) {
      OperationalResultsDialog.show(
        Get.context!,
        text: '提现失败',
        icon: 'assets/images/img_tc_sb.png',
        confirmTap: () {
          Get.back();
        }
      );
    } finally {
      EasyLoading.dismiss();
    }
  }

}